﻿package fj.ui
{
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	import fj.events.FJFaderEvent;

	public class FJFader extends MovieClip
	{
		private var _handler:MovieClip;
		private var _rail:MovieClip;
		
		private var _percent:Number;

		public function FJFader():void
		{
			_handler = getChildByName( "handler" ) as MovieClip;
			_rail = getChildByName( "rail" ) as MovieClip;

			_handler.buttonMode = true;
			
			_handler.addEventListener( MouseEvent.MOUSE_DOWN, handlerDown );
		}
		public function set percent( n:Number ):void
		{
			_percent = n;
			_handler.x = _rail.x + _percent * ( _rail.width / 100 );
			dispatchEvent( new FJFaderEvent( _percent ) );
		}
		public function get percent():Number
		{
			return _percent;
		}
		private function handlerDown( e:MouseEvent ):void
		{
			stage.addEventListener( MouseEvent.MOUSE_MOVE, handlerMove );
			stage.addEventListener( MouseEvent.MOUSE_UP, handlerUp );
		}
		private function handlerUp( e:MouseEvent ):void
		{
			stage.removeEventListener( MouseEvent.MOUSE_MOVE, handlerMove );
			stage.removeEventListener( MouseEvent.MOUSE_UP, handlerUp );
		}
		private function handlerMove( e:MouseEvent ):void
		{
			_handler.x = mouseX;
			if ( _handler.x < _rail.x ) {
				_handler.x = _rail.x;
			}
			if ( _handler.x > _rail.x + _rail.width ) {
				_handler.x = _rail.x + _rail.width;
			}
			_percent = ( _handler.x - _rail.x ) / ( _rail.width );
			dispatchEvent( new FJFaderEvent( _percent ) );
		}
	}
}